<template>
  <div>
    <div ref="captureElement" class="content-box">
      <h1>需要保存的内容</h1>
      <p>示例文本</p>
    </div>
    <button @click="saveAsImage">保存为图片</button>
  </div>
</template>

<script>
import html2canvas from 'html2canvas';

export default {
  methods: {
    saveAsImage() {
      html2canvas(this.$refs.captureElement).then(canvas => {
        const imgUrl = canvas.toDataURL('image/png');
        const link = document.createElement('a');
        link.download = 'screenshot.png';
        link.href = imgUrl;
        link.click();
      });

      /**
       * 高级配置（背景透明、跨域图片）
      html2canvas(this.$refs.captureElement, {
        backgroundColor: null, // 透明背景
        useCORS: true,         // 允许加载跨域图片
        scale: 2               // 提高分辨率
      }).then(canvas => { });
      
      */
    },
    /**
     * 处理移动端兼容性问题
    saveAsImage() {
      html2canvas(this.$refs.captureElement).then(canvas => {
        const imgUrl = canvas.toDataURL('image/png');
        // 移动端通过图片预览引导用户长按保存
        if (this.isMobile()) {
          ImagePreview([imgUrl]); // 使用 Vant 等 UI 库的预览组件
          this.$toast('请长按图片保存到相册');
        } else {
          // PC 端直接下载
          const link = document.createElement('a');
          link.href = imgUrl;
          link.download = 'screenshot.png';
          link.click();
        }
      });
    },
    isMobile() {
      return /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent);
    }
    */

  }
};
</script>

